const { eval_code } = require("./share_data");
const { format, toArray } = require("../utils/transform_tool");
const { BaseCommand } = require("./base");

class ModifyCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        let flags = data.flags || "";
        if (flags.indexOf("g") === -1) {
            flags += "g";
        }
        const reg = new RegExp(data.pattern, flags);
        let idx = 0;
        const replacers = toArray(data.replacer);
        const converters = toArray(data.converter);
        const ret = this.content.replace(reg, (...args) => {
            const replacer = replacers[idx] || data.default_replacer;
            const converter = converters[idx];
            if (replacer == null) {
                return args[0];
            }
            if (converter) {
                args[1] = eval_code(converter)(args[1]);
            }
            ++idx;
            return format(replacer, args);
        });
        return ret;
    }

    getRequireContent() {
        return true;
    }

    getRequiredParams() {
        return ["pattern"];
    }
}

module.exports = {
    ModifyCommand,
};
